package api

import (
	"vblog/apps/token"
	"vblog/conf"
	"vblog/ioc"
	"vblog/response"

	"github.com/gin-gonic/gin"
)

// func NewTokenApiHandler() *TokenApiHandler {
// 	return &TokenApiHandler{
// 		token: ioc.Controller.Get(token.AppName).(token.Service),
// 	}
// }

func init() {
	// 注册到ioc
	ioc.Api.Registry(token.AppName, &TokenApiHandler{})
}

type TokenApiHandler struct {
	token token.Service
}

// 实现Api IOC的方法
func (h *TokenApiHandler) Init() error {
	// 这里做一些初始化操作
	//
	h.token = ioc.Controller.Get(token.AppName).(token.Service)

	// 在vblog/api/v1 + tokens
	appRouter := conf.C().APP.RootRouter().Group(token.AppName)

	// 注册子路由
	h.Registry(appRouter)
	return nil
}

// 注册路由
func (h *TokenApiHandler) Registry(appRouter gin.IRouter) {
	// func (gin.IRoutes) POST(string, ...gin.HandlerFunc) gin.IRoutes
	// type HandlerFunc func(*Context)
	appRouter.POST("/", h.Login)
	appRouter.DELETE("/", h.Logout)
}

func (h *TokenApiHandler) Login(c *gin.Context) {
	req := token.NewIssueTokenRequest("", "")
	// 获取请求参数
	err := c.BindJSON(req)
	if err != nil {
		// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		// return

		response.Failed(c, err)
		return
	}

	tk, err := h.token.IssueToken(c, req)
	if err != nil {
		response.Failed(c, err)
		return
	}

	// 设置Cookie

	c.SetCookie(token.CookieName,
		tk.AccessToken,
		int(tk.AccessTokenExpiredAt),
		"",
		conf.C().APP.Domain, false, true,
	)

	response.Success(c, tk)
}

func (h *TokenApiHandler) Logout(c *gin.Context) {
	// req := token.NewRevolkTokenRequest("", "")
	// err := c.BindJSON(req)

	// DELETE方法不带body，要从cookie中获取

	accessToken, err := c.Cookie(token.CookieName)
	if err != nil {
		response.Failed(c, err)
		return
	}

	refreshToken := c.GetHeader(token.RefreshHeaderKey)

	req := token.NewRevolkTokenRequest(accessToken, refreshToken)

	tk, err := h.token.RevolkToken(c, req)
	if err != nil {
		response.Failed(c, err)
		return
	}

	response.Success(c, tk)

}
